import { defineStore } from "pinia";
import {
  listBands as listBandsLocal,
  listIcons as listIconsLocal,
  svgoPipe,
} from "../service/server";
import {
  init as initCos,
  listBands,
  listIcons,
  saveBand,
  deleteBand,
  addIcon,
  deleteIcon,
} from "../service/cos";

export const useStore = defineStore({
  id: "main",
  state: () => ({
    visitor: false,
    Bucket: "",
    Region: "",
    bands: [],
    icons: [],
  }),
  getters: {},
  actions: {
    async login(SecretId, SecretKey, Bucket, Region) {
      this.$state.Bucket = Bucket;
      this.$state.Region = Region;
      await initCos(SecretId, SecretKey, Bucket, Region);
    },
    async logout() {
      this.$reset();
      sessionStorage.clear();
    },
    async visit() {
      this.$state.visitor = true;
    },
    async refreshBandList() {
      const action = this.$state.visitor ? listBandsLocal : listBands;
      this.$state.bands = await action();
    },
    async getIcons(bandName) {
      // const action = this.$state.visitor ? listIconsLocal : listIcons;
      this.$state.icons = await listIcons(bandName);
    },
    async createBand(bandName) {
      await saveBand(bandName);
      await this.refreshBandList();
    },
    async deleteBand(bandName) {
      await deleteBand(bandName);
      await this.refreshBandList();
    },
    async createIcon(bandName, iconName, file) {
      const pipedSVGText = await svgoPipe(file);
      await addIcon(bandName, iconName, pipedSVGText);
      await this.getIcons(bandName);
    },
    async deleteIcon(bandName, iconName) {
      await deleteIcon(bandName, iconName);
      await this.getIcons(bandName);
    },
  },
});
